package orbit

import (
	"strings"

	"gddgame.cc/galaxy/binocle"
	"gddgame.cc/galaxy/core/sdk"
	"gddgame.cc/galaxy/satellite/formula/comet"
	"gddgame.cc/galaxy/server/composer"

	"gddgame.cc/galaxy/utils/def"
)

type ns struct {
	settings map[string]interface{}
}
type auth struct {
	openId  string
	nsMap   map[string]*ns
	version int
	region  string
}

func (auth *auth) Region() string {
	return auth.region
}

var (
	client *sdk.ServiceClient
	agent  binocle.Service
)

func AuthHandler(builder composer.Builder, a binocle.Service) error {
	var err error
	client, err = sdk.NewServerClient(builder)
	agent = a
	return err
}

func authHandle(context def.Context, packet *comet.AppPacket, authorization string, prevAuthority interface{}) (interface{}, error) {
	var a *auth
	if prevAuthority == nil {
		a = &auth{version: 0}
	} else {
		a = prevAuthority.(*auth)
	}
	appInfo, openId, data, err := client.ParseAccessToken(packet.Id, packet.Token, authorization)
	if err != nil {
		return nil, err
	}
	if a.openId != openId {
		// 如果更新用户，权限全部更新
		a.nsMap = make(map[string]*ns)
		a.openId = openId
	}
	// 权限结果，增量更新
	for key, _ := range data {
		if strings.Index(key, "orbit.") == 0 {
			item := strings.Split(strings.Replace(key, "orbit.", "", 1), ":")
			if _, ok := a.nsMap[item[0]]; !ok {
				a.nsMap[item[0]] = &ns{
					settings: make(map[string]interface{}),
				}
			}
			a.nsMap[item[0]].settings[item[1]] = data[key]
		}
	}
	a.version += 1

	// 用于关联container
	a.region = agent.FillName(appInfo.Name)

	return a, nil
}
